package elastic

import (
	"github.com/google/wire"
	es "github.com/olivere/elastic/v7"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"strings"
)

// ClientType 定义日志 client 结构体
type ClientType struct {
	Es     *es.Client
	logger *zap.Logger
}

// Client  logger连接类型
var Client ClientType

// Options log option
type Options struct {
	Urls     []string
	User     string
	Password string
}

// NewOptions new log option
func NewOptions(v *viper.Viper, logger *zap.Logger) (*Options, error) {
	var (
		err error
		o   = new(Options)
	)
	if err = v.UnmarshalKey("es", o); err != nil {
		return nil, errors.Wrap(err, "unmarshal elastic option error")
	}
	logger.Info("load es options success", zap.Any("es options", o))
	return o, err
}

// New new esClient
func New(o *Options) (*es.Client, error) {
	var (
		err      error
		esClient *es.Client
	)
	esClient, err = es.NewClient(
		es.SetSniff(false),
		es.SetURL(strings.Join(o.Urls, ",")),
		es.SetBasicAuth(o.User, o.Password),
	)
	if err != nil {
		return nil, err
	}
	Client.Es = esClient
	return esClient, nil
}

// ProviderSet dependency injection
var ProviderSet = wire.NewSet(New, NewOptions)
